<template>
  <div v-if="tool">
    <Suspense>
      <component :is="toolComponent" />
      <template #fallback>
        <div class="flex items-center justify-center p-4">
          <div class="text-center">
            <p class="text-gray-600">加载中...</p>
          </div>
        </div>
      </template>
    </Suspense>
  </div>
  <div v-else class="flex items-center justify-center h-screen">
    <div class="text-center">
      <h2 class="text-2xl font-bold text-gray-700">工具不存在</h2>
      <router-link to="/" class="mt-4 text-blue-500 hover:text-blue-600">返回首页</router-link>
    </div>
  </div>
  <n-page-header @back="goBack" :title="tool?.title || '工具详情'">
    <template #extra>
      <n-tag>{{ tool?.category }}</n-tag>
    </template>
    <div style="margin-top:16px;">
      <div>{{ tool?.description }}</div>
      <div style="margin-top:24px;color:#888;">（此处可扩展具体工具功能区）</div>
    </div>
  </n-page-header>
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, markRaw, onErrorCaptured } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToolsStore } from '../store/tools'
import type { Tool } from '../store/tools'

const route = useRoute()
const router = useRouter()
const toolsStore = useToolsStore()

const tool = computed<Tool | undefined>(() => 
  toolsStore.getToolById(route.params.id as string)
)

const toolComponent = computed(() => {
  if (!tool.value?.component) return null
  return defineAsyncComponent({
    loader: () => import(`../pages/tools/${tool.value!.component}.vue`),
    timeout: 5000,
    errorComponent: {
      template: `
        <div class="text-center p-4">
          <p class="text-red-500">加载组件失败，请刷新页面重试</p>
        </div>
      `
    },
    loadingComponent: {
      template: `
        <div class="text-center p-4">
          <p class="text-gray-600">加载中...</p>
        </div>
      `
    }
  })
})

onErrorCaptured((error) => {
  console.error('Component loading error:', error)
  return false
})

function goBack() {
  router.back()
}
</script>